﻿var access_token;
var prev_access_token, cur_access_token;
window.FB = FBWinJS;
var share = false;
var myFriends = null;
var playCheck = false;
var cur_id=1;
var prev_id=0;

/*Enter your app-id from facebook for your app here.*/
FB.options({
    appId: 'xxxxxxxxxxxxxxxxxxx'
});

(function () {
    "use strict";
    var currentApp = Windows.ApplicationModel.Store.CurrentAppSimulator;
    var page = WinJS.UI.Pages.define("/html/feedback.html", {
        ready: function (element, options) {
            //deleteDB();

            /*The code in ready function goes into the block of your app.load() function */
            createDB();
            document.getElementById("viewReviews").addEventListener("click", viewReview, false);
            document.getElementById("submitReview").addEventListener("click", submitAdd, false);
            document.getElementById("feed").addEventListener("click", feed, false);
        },
        unload: function () {
            /*The code in unload function goes into the block of your app.unload() function */

        }
    });
    
    function feed() {
        
        Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri("ms-windows-store:REVIEW?PFN=" + Windows.ApplicationModel.Package.current.id.familyName));
    }

    function submitAdd() {

        var dbRequest = window.indexedDB.open("AppDB", 1);

        // Add asynchronous callback functions
        dbRequest.onerror = function () { WinJS.log && WinJS.log("Error opening database.", "sample", "error"); };
        dbRequest.onsuccess = function (evt) { dbSuccess(evt); };
        dbRequest.onupgradeneeded = function (evt) { WinJS.log && WinJS.log("Database wrong version.", "sample", "error"); if (SdkSample.db) { SdkSample.db.close(); } };
        dbRequest.onblocked = function () { WinJS.log && WinJS.log("Database access blocked.", "sample", "error"); };

        function dbSuccess(evt) {
            // If the database was previously loaded, close it... this keeps the database from becoming blocked for later deletes
            if (SdkSample.db) {
                SdkSample.db.close();
            }
            SdkSample.db = evt.target.result;
            if (SdkSample.db.objectStoreNames.length === 0) {
                WinJS.log && WinJS.log("Database schema does not exist. Complete the first scenario before continuing.", "sample", "error");
                SdkSample.db.close();
                SdkSample.db = null;
                window.indexedDB.deleteDatabase("AppDB", 1);
            } else {
                submitReviewHelper(evt);

            }
        }

        function submitReviewHelper(evt) {

            if (evt.type === "success") {
                var txn = SdkSample.db.transaction(["feedback"], "readwrite");

                txn.oncomplete = function () {
                    // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
                };
                txn.onerror = function () {

                    WinJS.log && WinJS.log("Some error occured, feedback could'nt be added", "sample", "error");
                };
                txn.onabort = function () {

                    WinJS.log && WinJS.log("Some  error occured, feedback could'nt be added", "sample", "error");
                };

                var feedbackStore = txn.objectStore("feedback");

                var feed = document.getElementById("feedB").innerText;
                var ratingControl = document.getElementById("feedbackRating").winControl;
                var userRating = ratingControl.userRating;

                // var check = 6;
                var d = new Date();


                feedbackStore.openCursor().onsuccess = function (e) {
                    if (!e.target.result) {
                       // WinJS.log && WinJS.log("No Reviews found.", "sample", "error");
                        cur_id = 0;

                    }
                };

                if (prev_id == 0) {
                    cur_id = 1
                }

                var entry = {
                   id:d,
                   feedbackDate: d,
                   rating: userRating,
                   text: feed
                }


                var addResult = feedbackStore.add(entry);
                //var check = 6;

                WinJS.log && WinJS.log("Review Submitted.", "sample", "error");
            }
        }
    }


    function viewReview() {

        var dbRequest = window.indexedDB.open("AppDB", 1);

        // Add asynchronous callback functions
        dbRequest.onerror = function () { WinJS.log && WinJS.log("Error opening database.", "sample", "error"); };
        dbRequest.onsuccess = function (evt) { dbSuccess(evt); };
        dbRequest.onupgradeneeded = function (evt) { WinJS.log && WinJS.log("Database wrong version.", "sample", "error"); if (SdkSample.db) { SdkSample.db.close(); } };
        dbRequest.onblocked = function () { WinJS.log && WinJS.log("Database access blocked.", "sample", "error"); };

        function dbSuccess(evt) {
            // If the database was previously loaded, close it... this keeps the database from becoming blocked for later deletes
            if (SdkSample.db) {
                SdkSample.db.close();
            }
            SdkSample.db = evt.target.result;
            if (SdkSample.db.objectStoreNames.length === 0) {
                WinJS.log && WinJS.log("Database schema does not exist. Complete the first scenario before continuing.", "sample", "error");
                SdkSample.db.close();
                SdkSample.db = null;
                window.indexedDB.deleteDatabase("AppDB", 1);
            } else {
                viewReviewHelper(evt);

            }
        }

        function viewReviewHelper(evt) {

            if (evt.type === "success") {
                var txn = SdkSample.db.transaction(["feedback"], "readwrite");

                txn.oncomplete = function () {
                    // WinJS.log && WinJS.log("Database entry found.", "sample", "status");
                };
                txn.onerror = function () {

                    WinJS.log && WinJS.log("No Reviews found.", "sample", "error");
                };
                txn.onabort = function () {

                    WinJS.log && WinJS.log("No Reviews found.", "sample", "error");
                };

                var feedbackStore = txn.objectStore("feedback");


                var list = [];

                feedbackStore.openCursor().onsuccess = function (e) {

                    var cursor = e.target.result;

                    if (cursor) {
                        list.push(cursor.value);
                        cursor.continue();
                    }
                    else {
                        console.log(list);
                        if (list == []) {


                            WinJS.log && WinJS.log("No Reviews found.", "sample", "error");

                        }
                        else {

                            function mySort(objToSort, fieldToSort) {
                                var sortFunc = function (a, b) {
                                    var answer = 0;
                                    if (a[fieldToSort] > b[fieldToSort])
                                        answer = -1;
                                    else if (a[fieldToSort] < b[fieldToSort])
                                        answer = 1;
                                    return answer;
                                };

                                return objToSort.sort(sortFunc);
                            }

                            var msg = "sorted by rating:";
                            var sortedByRating = mySort(list, "rating");
                            for (var i = 0, n = sortedByRating.length; i < n; i++)
                                msg += "\n\n" + "Rating: " + sortedByRating[i].rating + "\nfeedback: " + sortedByRating[i].text + "\ndate:" + sortedByRating[i].feedbackDate;

                            WinJS.log && WinJS.log(msg, "sample", "status")


                        }

                    }

                };

            }

        }
    }

    var newCreate = false;
    
    function createDB() {
        // Create the request to open the database, named BookDB. If it doesn't exist, create it and immediately
        // upgrade to version 1.
        var dbRequest = window.indexedDB.open("AppDB", 1);

        // Add asynchronous callback functions
        dbRequest.onerror = function () { WinJS.log && WinJS.log("Error creating database.", "sample", "error"); };
        dbRequest.onsuccess = function (evt) { dbSuccess(evt); };
        dbRequest.onupgradeneeded = function (evt) { dbVersionUpgrade(evt); };
        dbRequest.onblocked = function () { WinJS.log && WinJS.log("Database create blocked.", "sample", "error"); };

        // Reset the flag that indicates whether this is a new creation request. 
        // Assume that the database was previously created.
        newCreate = false;
    }

    function deleteDB() {

        // Close and clear the handle to the database, held in the parent SdkSample namespace.
        if (SdkSample.db) {
            SdkSample.db.close();
        }
        SdkSample.db = null;
        var dbRequest = window.indexedDB.deleteDatabase("AppDB");
        dbRequest.onerror = function () { WinJS.log && WinJS.log("Error deleting database.", "sample", "error"); };
        dbRequest.onsuccess = function () { WinJS.log && WinJS.log("Database deleted.", "sample", "status"); };
        dbRequest.onblocked = function () {
            WinJS.log && WinJS.log("Database delete blocked.", "sample", "error");
        };
    }

    // Whenever an IndexedDB is created, the version is set to "", but can be immediately upgraded by calling createDB. 
    function dbVersionUpgrade(evt) {

        // If the database was previously loaded, close it. 
        // Closing the database keeps it from becoming blocked for later delete operations.
        if (SdkSample.db) {
            SdkSample.db.close();
        }
        SdkSample.db = evt.target.result;

        // Get the version update transaction handle, since we want to create the schema as part of the same transaction.
        var txn = evt.target.transaction;

        // Create the books object store, with an index on the book title. Note that we set the returned object store to a variable
        // in order to make further calls (index creation) on that object store.
        var userInfoStore = SdkSample.db.createObjectStore("userInfo", { keyPath: "id" });
        userInfoStore.createIndex("fb_id", "fb_id", { unique: true });
        userInfoStore.createIndex("name", "name", { unique: false });



        // Create the authors object store.
        var feedbackStore = SdkSample.db.createObjectStore("feedback", { keyPath: "id", autoincrement: true });


        // Create the book checkout status object store. Note that new object stores can only be created/deleted as part of the version change.
        // transaction that we're adding to in this function.
        //SdkSample.db.createObjectStore("checkout", { keyPath: "id" });

        // Once the creation of the object stores is finished (they are created asynchronously), log success.
        txn.oncomplete = function () { WinJS.log && WinJS.log("Database schema created.", "sample", "status"); };
        newCreate = true;
    }

    function dbSuccess(evt) {

        // Log whether the app tried to create the database when it already existed. 
        if (!newCreate) {
            // Close this additional database request
            var db = evt.target.result;
            db.close();

            WinJS.log && WinJS.log("Database schema already exists.", "sample", "error");
            return;
        }
    }

    
    //fb stuff
    // UTILITIES

    // For logging responses
    function logResponse(response) {
        if (typeof console !== 'undefined')
            console.log('The response was', response);
    }

    // AUTHENTICATION
    function loginClicked() {

        if (access_token) {
            updateUserInfo();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {

                        
                        access_token = result.access_token;
                        //updateUserInfo();
                    }
                }
            });
        }
    }

    function postClicked() {

        FB.setAccessToken(access_token);

        var body = 'I like this app';
        FB.api('me/feed', 'post', {
            message: body, link: "", caption: "Social Promotional Video", name: "TicTac", source: "http://ie.microsoft.com/testdrive/Videos/BehindIE9AllAroundFast/Video.mp4", type: 'video'
        }, function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                WinJS.log && WinJS.log("Unable to update points, share failed.", "sample", "error");
                return;
            }
            console.log('Post Id: ' + res.id);
            WinJS.log && WinJS.log("Thank You for sharing the promo video.", "sample", "error");
            share = true;


            if (share === true ) {
                var a = document.getElementById("points").innerText;
                var b = parseInt(a);
                b = b + 50;
                document.getElementById("points").innerText = b;
                share = false;
            }
            else {
                WinJS.log && WinJS.log("Unable to update points, share failed.", "sample", "error");
            }
        });



    }

    function askForPermissions(scope, callback) {

        var redirectUri = 'https://www.facebook.com/connect/login_success.html',
            loginUrl = FB.getLoginUrl({ scope: scope });

        try {

            Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
                Windows.Security.Authentication.Web.WebAuthenticationBroker.default,
                new Windows.Foundation.Uri(loginUrl),
                new Windows.Foundation.Uri(redirectUri))
                .then(function success(result) {
                    if (result.responseStatus == 2) {
                        console.log('error: ' + result.responseerrordetail);
                        callback(new Error(result.responseerrordetail));
                        return;
                    }

                    var parser = document.createElement('a');
                    parser.href = result.responseData;

                    var qs = extractQuerystring(parser.hash.substr(1).split('&'));

                    if (qs.error) {
                        // most likely user clicked don't allow
                        console.log('error: ' + qs.error + ' : ' + qs.error_description);
                        return;
                    }

                    // set it as the default access token.
                    FB.setAccessToken(qs.access_token);

                    callback(null, qs);

                }, function error(err) {
                    console.log('Error Number: ' + err.number);
                    console.log('Error Message: ' + err.message);
                    callback(new Error(err.message));
                });

        } catch (e) {
            // error launching web auth
            console.log(e);
        }
    }


    function updateUserInfo(response) {
        FB.api('/me',
          { fields: "name,first_name,picture" },
          function (response) {
              logResponse(response);
              //response.id

              //adding info to userInfo table in the AppDB database
              var dbRequest = window.indexedDB.open("AppDB", 1);

              // Add asynchronous callback functions
              dbRequest.onerror = function () { WinJS.log && WinJS.log("Error opening database.", "sample", "error"); };
              dbRequest.onsuccess = function (evt) { dbSuccess(evt); };
              dbRequest.onupgradeneeded = function (evt) { WinJS.log && WinJS.log("Database wrong version.", "sample", "error"); if (SdkSample.db) { SdkSample.db.close(); } };
              dbRequest.onblocked = function () { WinJS.log && WinJS.log("Database access blocked.", "sample", "error"); };


              function dbSuccess(evt) {
                  // If the database was previously loaded, close it... this keeps the database from becoming blocked for later deletes
                  if (SdkSample.db) {
                      SdkSample.db.close();
                  }
                  SdkSample.db = evt.target.result;
                  if (SdkSample.db.objectStoreNames.length === 0) {
                      WinJS.log && WinJS.log("Database schema does not exist. Complete the first scenario before continuing.", "sample", "error");
                      SdkSample.db.close();
                      SdkSample.db = null;
                      window.indexedDB.deleteDatabase("AppDB", 1);
                  } else {
                      addData(evt);

                  }
              }

              function addData(evt) {
                  if (evt.type === "success") {
                      var txn = SdkSample.db.transaction(["userInfo"], "readwrite");

                      txn.oncomplete = function () {
                          WinJS.log && WinJS.log("Database entry added.", "sample", "status");
                          document.getElementById("currentLicenseMode").innerText = "Current license mode: Trial license";
                      };
                      txn.onerror = function () {
                          WinJS.log && WinJS.log("Unable to add to database, db entry may already exist.", "sample", "error");
                      };
                      txn.onabort = function () {
                          WinJS.log && WinJS.log("Unable to add to database, db entry may already exist.", "sample", "error");
                      };

                      var d = new Date();

                      var future = new Date();
                      future.setDate(future.getDate() + 30);
                      //var dExp = d + 30;
                      var userInfoStore = txn.objectStore("userInfo");
                      var entry = {
                          id: response.id,
                          name: response.name,
                          db_IsActive: true,
                          db_IsTrial: true,
                          Total_Shares: 0,
                          fb_id: response.id,
                          trialStartDate: d,
                          trialEndDate: future

                      }
                      var addResult = userInfoStore.add(entry);

                      var request = userInfoStore.get(response.id);

                      request.onsuccess = function (e) {
                          console.log(e.target.result);
                      };

                      var list = [];

                      userInfoStore.openCursor().onsuccess = function (e) {
                          var cursor = e.target.result;

                          if (cursor) {
                              list.push(cursor.value);
                              cursor.continue();
                          }
                          else {
                              console.log(list);
                          }
                      };

                  }

              }

          });
    }

    function shareProduct2() {

        loginClicked();
    }

})();